package com.example.homework.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.bumptech.glide.Glide
import com.example.homework.databinding.PhotoRecyclerViewItemBinding
import com.example.homework.models.Photo

class PhotosRecyclerViewAdapter(val onClick: (String) -> Unit) :
    Adapter<PhotosRecyclerViewHolder>() {
    private var values: List<Photo> = emptyList()
    fun setData(data: List<Photo>) {
        values = data
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotosRecyclerViewHolder {
        val binding: PhotoRecyclerViewItemBinding =
            PhotoRecyclerViewItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        ViewCompat.setTransitionName(binding.photoImageView, "photoImageView")
        return PhotosRecyclerViewHolder(binding)
    }

    override fun getItemCount(): Int = values.size

    override fun onBindViewHolder(holder: PhotosRecyclerViewHolder, position: Int) {
        val item: Photo = values[position]
        with(holder.binding) {
            cameraTextView.text = item.camera.name
            dateTextView.text = item.earthDate
            solTextView.text = item.sol
            roverTextView.text = item.rover.name
            item?.let {
                Glide.with(photoImageView.context).load(item.imgSrc)
                    .placeholder(android.R.drawable.progress_indeterminate_horizontal)
                    .error(android.R.drawable.stat_notify_error).into(photoImageView)
            }
            root.setOnClickListener {
                onClick(item.imgSrc)
            }
        }
    }
}